import OpenAI from 'openai';

export class AIService {
    constructor() {
        this.client = new OpenAI({
            baseURL: import.meta.env.VITE_AI_API_BASE_URL,
            apiKey: import.meta.env.VITE_AI_API_KEY,
            dangerouslyAllowBrowser: true
        });
    }

    async generateResponse(userMessage, onStream) {
        try {
            const response = await this.client.chat.completions.create({
                model: 'deepseek-chat',
                messages: [
                    { role: 'system', content: '你是一个友好的AI助手，能够提供准确和有帮助的回答。' },
                    { role: 'user', content: userMessage }
                ],
                temperature: 0.7,
                max_tokens: 1000,
                stream: true
            });

            let fullResponse = '';
            for await (const chunk of response) {
                const content = chunk.choices[0]?.delta?.content || '';
                fullResponse += content;
                if (onStream) {
                    onStream(fullResponse);
                }
            }

            return fullResponse;
        } catch (error) {
            console.error('AI Service Error:', error);
            throw new Error('无法获取AI响应');
        }
    }

    async generateTitle(messages) {
        try {
            const lastUserMessage = messages.find(m => m.sender === 'user')?.content || '';
            const prompt = `请为这个对话生成一个简短的标题（不超过15个字）。对话的第一条消息是：${lastUserMessage}`;

            const response = await this.client.chat.completions.create({
                model: 'deepseek-chat',
                messages: [
                    { role: 'system', content: '你是一个帮助生成对话标题的助手。请生成简短、具体的标题。' },
                    { role: 'user', content: prompt }
                ],
                temperature: 0.7,
                max_tokens: 50,
                stream: false
            });

            return response.choices[0]?.message?.content?.replace(/["""]/g, '') || '新对话';
        } catch (error) {
            console.error('Generate Title Error:', error);
            return '新对话';
        }
    }
}